package com.hobart.learning.lagou.edu.service.impl;

import com.hobart.learning.lagou.edu.annotation.Autowired;
import com.hobart.learning.lagou.edu.annotation.Service;
import com.hobart.learning.lagou.edu.annotation.Transactional;
import com.hobart.learning.lagou.edu.dao.IAccountDao;
import com.hobart.learning.lagou.edu.pojo.Account;
import com.hobart.learning.lagou.edu.service.ITransferService;

/**
 * @author ：hobart
 * @date ：Created in 2021-1-28 15:05
 * @description： 转账 Service
 * @version: 1.0
 */
@Service
public class TransferServiceImpl implements ITransferService {

    // 第一版
    //private IAccountDao accountDao = new AcountDaoImpl();

    // 第二版
    //private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");

    // 第三版
//    private IAccountDao accountDao;
//
//    public void setAccountDao(IAccountDao accountDao) {
//        this.accountDao = accountDao;
//    }

    @Autowired
    private IAccountDao accountDao;

    // 第一版
//    @Override
//    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
//
//        Account from = accountDao.queryAccountByCardNo(fromCardNo);
//        Account to = accountDao.queryAccountByCardNo(toCardNo);
//
//        from.setMoney(from.getMoney()-money);
//        to.setMoney(to.getMoney()+money);
//
//        accountDao.updateAccountByCardNo(to);
//        int i = 1/0;
//        accountDao.updateAccountByCardNo(from);
//
//    }

    // 第四版
//    @Override
//    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
//        try {
//            TransactionManager.getInstance().beginTransaction();
//            Account from = accountDao.queryAccountByCardNo(fromCardNo);
//            Account to = accountDao.queryAccountByCardNo(toCardNo);
//
//            from.setMoney(from.getMoney()-money);
//            to.setMoney(to.getMoney()+money);
//
//            accountDao.updateAccountByCardNo(to);
//            int i = 1/0;
//            accountDao.updateAccountByCardNo(from);
//            TransactionManager.getInstance().commitTransaction();
//        } catch (Exception e) {
//            e.printStackTrace();
//            TransactionManager.getInstance().rollbackTransaction();
//            throw e;
//        }
//
//    }

    // 第五版
    @Override
    @Transactional
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {

        Account from = accountDao.queryAccountByCardNo(fromCardNo);
        Account to = accountDao.queryAccountByCardNo(toCardNo);

        from.setMoney(from.getMoney()-money);
        to.setMoney(to.getMoney()+money);

        accountDao.updateAccountByCardNo(to);
        // 模拟 事物回滚
        int i = 1/0;
        accountDao.updateAccountByCardNo(from);

    }
}
